/**
 * 小程序性能监控工具
 * 基于性能优化指南实现的监控和优化工具
 */

// setData性能监控
let setDataStats = {
  totalCalls: 0,
  totalTime: 0,
  slowCalls: [],
  dataSize: []
};

/**
 * 增强的setData监控
 */
function enhanceSetData() {
  const originalSetData = Page.prototype.setData;
  
  Page.prototype.setData = function(data, callback) {
    const startTime = Date.now();
    const dataSize = JSON.stringify(data).length;
    
    // 记录统计信息
    setDataStats.totalCalls++;
    setDataStats.dataSize.push(dataSize);
    
    // 警告大数据量setData
    if (dataSize > 50000) { // 50KB
      console.warn('⚠️ Large setData detected:', {
        size: `${(dataSize / 1024).toFixed(2)}KB`,
        keys: Object.keys(data),
        page: this.route
      });
    }
    
    // 执行原始setData
    originalSetData.call(this, data, () => {
      const endTime = Date.now();
      const duration = endTime - startTime;
      
      setDataStats.totalTime += duration;
      
      // 记录慢调用
      if (duration > 16) { // 大于一帧时间
        setDataStats.slowCalls.push({
          duration,
          size: dataSize,
          keys: Object.keys(data),
          page: this.route,
          timestamp: new Date().toISOString()
        });
        
        console.warn('🐌 Slow setData detected:', {
          duration: `${duration}ms`,
          size: `${(dataSize / 1024).toFixed(2)}KB`,
          keys: Object.keys(data),
          page: this.route
        });
      }
      
      callback && callback();
    });
  };
}

/**
 * 获取setData性能统计
 */
function getSetDataStats() {
  const avgTime = setDataStats.totalCalls > 0 
    ? (setDataStats.totalTime / setDataStats.totalCalls).toFixed(2) 
    : 0;
  
  const avgSize = setDataStats.dataSize.length > 0
    ? (setDataStats.dataSize.reduce((a, b) => a + b, 0) / setDataStats.dataSize.length / 1024).toFixed(2)
    : 0;
  
  return {
    totalCalls: setDataStats.totalCalls,
    totalTime: setDataStats.totalTime,
    avgTime: `${avgTime}ms`,
    avgSize: `${avgSize}KB`,
    slowCallsCount: setDataStats.slowCalls.length,
    slowCalls: setDataStats.slowCalls.slice(-10) // 最近10次慢调用
  };
}

/**
 * 智能缓存管理器
 */
class SmartCache {
  constructor() {
    this.cachePrefix = 'smart_cache_';
    this.defaultTTL = 5 * 60 * 1000; // 5分钟
  }
  
  /**
   * 设置缓存
   */
  set(key, data, ttl = this.defaultTTL) {
    const cacheData = {
      data,
      timestamp: Date.now(),
      ttl,
      size: JSON.stringify(data).length
    };
    
    try {
      wx.setStorageSync(`${this.cachePrefix}${key}`, cacheData);
    } catch (error) {
      console.error('Cache set failed:', error);
      // 存储失败时清理旧缓存
      this.cleanup();
    }
  }
  
  /**
   * 获取缓存
   */
  get(key) {
    try {
      const cacheData = wx.getStorageSync(`${this.cachePrefix}${key}`);
      
      if (!cacheData) {
        return null;
      }
      
      const now = Date.now();
      const isExpired = now - cacheData.timestamp > cacheData.ttl;
      
      if (isExpired) {
        wx.removeStorageSync(`${this.cachePrefix}${key}`);
        return null;
      }
      
      return cacheData.data;
      
    } catch (error) {
      console.error('Cache get failed:', error);
      return null;
    }
  }
  
  /**
   * 检查缓存是否存在且有效
   */
  has(key) {
    return this.get(key) !== null;
  }
  
  /**
   * 删除缓存
   */
  remove(key) {
    try {
      wx.removeStorageSync(`${this.cachePrefix}${key}`);
    } catch (error) {
      console.error('Cache remove failed:', error);
    }
  }
  
  /**
   * 清理过期缓存
   */
  cleanup() {
    try {
      const info = wx.getStorageInfoSync();
      const cacheKeys = info.keys.filter(key => key.startsWith(this.cachePrefix));
      const now = Date.now();
      let cleanedCount = 0;
      
      cacheKeys.forEach(key => {
        try {
          const cacheData = wx.getStorageSync(key);
          if (cacheData && (now - cacheData.timestamp > cacheData.ttl)) {
            wx.removeStorageSync(key);
            cleanedCount++;
          }
        } catch (error) {
          // 如果读取失败，直接删除
          wx.removeStorageSync(key);
          cleanedCount++;
        }
      });
      

      
    } catch (error) {
      console.error('Cache cleanup failed:', error);
    }
  }
  
  /**
   * 获取缓存统计信息
   */
  getStats() {
    try {
      const info = wx.getStorageInfoSync();
      const cacheKeys = info.keys.filter(key => key.startsWith(this.cachePrefix));
      const now = Date.now();
      
      let totalSize = 0;
      let validCount = 0;
      let expiredCount = 0;
      
      cacheKeys.forEach(key => {
        try {
          const cacheData = wx.getStorageSync(key);
          if (cacheData) {
            totalSize += cacheData.size || 0;
            if (now - cacheData.timestamp > cacheData.ttl) {
              expiredCount++;
            } else {
              validCount++;
            }
          }
        } catch (error) {
          expiredCount++;
        }
      });
      
      return {
        totalItems: cacheKeys.length,
        validItems: validCount,
        expiredItems: expiredCount,
        totalSize: `${(totalSize / 1024).toFixed(2)}KB`,
        storageUsage: `${(info.currentSize / 1024).toFixed(2)}KB / ${(info.limitSize / 1024).toFixed(2)}KB`
      };
      
    } catch (error) {
      console.error('Get cache stats failed:', error);
      return null;
    }
  }
}

/**
 * 页面加载性能监控
 */
function trackPagePerformance(pageName) {
  const startTime = Date.now();
  
  return {
    markReady() {
      const loadTime = Date.now() - startTime;
      
      // 记录到性能日志
      const perfLog = wx.getStorageSync('perf_log') || [];
      perfLog.push({
        page: pageName,
        loadTime,
        timestamp: new Date().toISOString()
      });
      
      // 只保留最近50条记录
      if (perfLog.length > 50) {
        perfLog.splice(0, perfLog.length - 50);
      }
      
      wx.setStorageSync('perf_log', perfLog);
      
      return loadTime;
    }
  };
}

/**
 * 图片预加载工具（小程序版本 - 使用普通加载）
 * 注意：小程序环境中wx.createImage不存在，改为使用wx.getImageInfo进行图片验证
 */
function preloadImages(urls) {
  if (!Array.isArray(urls)) {
    urls = [urls];
  }

  
  // 小程序中直接返回成功，不做实际预加载
  // 图片会在实际使用时按需加载
  const promises = urls.map(url => {
    return new Promise((resolve) => {
      if (url && typeof url === 'string') {
        // 可选：使用 wx.getImageInfo 验证图片有效性
        // 但为了性能考虑，这里直接返回成功
        resolve(url);
      } else {
        console.warn(`⚠️ 无效图片URL: ${url}`);
        resolve(null);
      }
    });
  });
  
  return Promise.all(promises);
}

/**
 * 防抖函数
 */
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

/**
 * 节流函数
 */
function throttle(func, limit) {
  let inThrottle;
  return function executedFunction(...args) {
    if (!inThrottle) {
      func.apply(this, args);
      inThrottle = true;
      setTimeout(() => inThrottle = false, limit);
    }
  };
}

// 创建全局缓存实例
const smartCache = new SmartCache();

// 初始化性能监控
function initPerformanceMonitor() {
  enhanceSetData();
  
  // 定时清理缓存
  setInterval(() => {
    smartCache.cleanup();
  }, 10 * 60 * 1000); // 每10分钟清理一次

}

module.exports = {
  initPerformanceMonitor,
  getSetDataStats,
  smartCache,
  trackPagePerformance,
  preloadImages,
  debounce,
  throttle
};
